import java.util.Timer;
import java.util.concurrent.PriorityBlockingQueue;

class Mytask implements Comparable<Mytask>{
    private Runnable runnable;
    private long time;
    public Mytask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }
    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(Mytask o) {
        return (int) (this.time-o.time);//时间小的在前，时间大的在后
    }
}


class MyTimer{
    private PriorityBlockingQueue<Mytask> queue=new PriorityBlockingQueue<>();
    public void schedule(Runnable runnable,long delay){
        Mytask task=new Mytask(runnable,delay);
        queue.put(task);
        //每次插入 成功之后，都唤醒一下扫描线程，让线程重新检查一下队首的任务看是否时间到要执行
        synchronized (locker){
            locker.notify();
        }
    }

    private Object locker=new Object();

    public MyTimer(){
        Thread t=new Thread(()->{
            while(true){
                try {
                    Mytask task=queue.take();
                    long curTime=System.currentTimeMillis();
                    if(curTime<task.getTime()){
                        queue.put(task);
                        //指定一个等待时间
                        synchronized (locker){//wait可以中途被唤醒，sleep不可以中途被唤醒
                            locker.wait(task.getTime()-curTime  );
                        }
                    }else{//时间到了，执行任务
                        task.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}

public class Demo24 {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello timer！");
            }
        },3000);
        System.out.println("main");
    }
}
